package com.abc.recycling.mapper;

import com.abc.recycling.domain.SysConfig;
import org.apache.ibatis.annotations.*;
import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface SysConfigMapper {
    
    // 插入配置
    @Insert("INSERT INTO sys_config(name, config_key, config_value, is_system, type, remark, status, create_time) " +
            "VALUES(#{name}, #{configKey}, #{configValue}, #{isSystem}, #{type}, #{remark}, #{status}, #{createTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(SysConfig config);
    
    // 更新配置
    @Update("UPDATE sys_config SET name = #{name}, config_value = #{configValue}, type = #{type}, " +
            "remark = #{remark}, status = #{status}, update_time = #{updateTime} " +
            "WHERE id = #{id} AND is_system = 0")
    int update(SysConfig config);
    
    // 根据ID查询配置
    @Select("SELECT * FROM sys_config WHERE id = #{id}")
    SysConfig findById(Long id);
    
    // 根据键名查询配置
    @Select("SELECT * FROM sys_config WHERE config_key = #{configKey} AND status = 1")
    SysConfig findByKey(String configKey);
    
    // 查询所有配置
    @Select("SELECT * FROM sys_config ORDER BY create_time DESC")
    List<SysConfig> findAll();
    
    // 搜索配置
    @Select("<script>" +
            "SELECT * FROM sys_config WHERE 1=1" +
            "<if test='name != null and name != \"\"'> AND name LIKE CONCAT('%', #{name}, '%')</if>" +
            "<if test='configKey != null and configKey != \"\"'> AND config_key LIKE CONCAT('%', #{configKey}, '%')</if>" +
            "<if test='type != null and type != \"\"'> AND type = #{type}</if>" +
            "<if test='status != null'> AND status = #{status}</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    List<SysConfig> search(String name, String configKey, String type, Integer status);
    
    // 更新配置状态
    @Update("UPDATE sys_config SET status = #{status}, update_time = #{updateTime} " +
            "WHERE id = #{id} AND is_system = 0")
    int updateStatus(Long id, Integer status, LocalDateTime updateTime);
    
    // 删除配置
    @Delete("DELETE FROM sys_config WHERE id = #{id} AND is_system = 0")
    int deleteById(Long id);
    
    // 检查键名是否存在
    @Select("SELECT COUNT(*) FROM sys_config WHERE config_key = #{configKey} AND id != #{excludeId}")
    int checkKeyExists(String configKey, Long excludeId);
} 